import { delData, getData, listData } from '@/api/system/dict/data'
import { optionselect as getDictOptionselect, getType } from '@/api/system/dict/type'
import DictTag from '@/components/dict-tag/index.vue'
import useDictStore from '@/store/modules/dict'
import { formatDate } from '@/utils/common'
import { useDicts } from '@/utils/dict'
import type { PaginationProps } from '@pureadmin/table'
import { ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute } from 'vue-router'

export function useConfig() {
  const data = reactive({
    form: {
      dictCode: undefined,
      dictLabel: undefined,
      dictValue: undefined,
      dictType: undefined,
      cssClass: undefined,
      listClass: 'default',
      dictSort: 0,
      status: '0',
      remark: undefined,
    },
    queryParams: {
      dictType: undefined,
      dictLabel: undefined,
      status: undefined,
    },
  })
  const { form, queryParams } = toRefs(data)
  const dictCode = ref(0)
  const title = ref('')

  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSelection = true

  const dataList = ref([])
  const loading = ref(true)

  const typeOptions = ref([])
  /** 当前展示的字典类型数据 */
  const currentDictType = ref('')

  const formDialogVisible = ref(false)
  const { sys_normal_disable } = useDicts('sys_normal_disable')

  const route = useRoute()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
      hide: ({ checkList }) => !checkList.includes('勾选列'),
    },
    {
      label: '序号',
      type: 'index',
      width: 70,
      hide: ({ checkList }) => !checkList.includes('序号列'),
    },
    {
      label: '字典编码',
      prop: 'dictCode',
      minWidth: 100,
    },
    {
      label: '字典标签',
      prop: 'dictLabel',
      minWidth: 150,
      cellRenderer: (scope) =>
        scope.row.listClass == '' || scope.row.listClass == 'default' ? (
          <span>{scope.row.dictLabel}</span>
        ) : (
          <el-tag type={scope.row.listClass == 'primary' ? '' : scope.row.listClass}>
            {scope.row.dictLabel}
          </el-tag>
        ),
    },
    {
      label: '字典键值',
      prop: 'dictValue',
      minWidth: 150,
    },
    {
      label: '字典排序',
      prop: 'dictSort',
      minWidth: 100,
    },
    {
      label: '状态',
      prop: 'status',
      minWidth: 120,
      cellRenderer: (scope) => {
        return <DictTag options={sys_normal_disable} value={scope.row.status} />
      },
    },
    {
      label: '备注',
      prop: 'remark',
      minWidth: 120,
    },
    {
      label: '创建时间',
      minWidth: 180,
      prop: 'createTime',
      formatter: ({ createTime }) => formatDate(createTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 180,
      slot: 'operation',
    },
  ]

  /** 重置新增的表单  */
  function reset() {
    form.value = {
      dictCode: undefined,
      dictLabel: undefined,
      dictValue: undefined,
      dictType: undefined,
      cssClass: undefined,
      listClass: 'default',
      dictSort: 0,
      status: '0',
      remark: undefined,
    }
  }

  /** 查询字典类型详细 */
  function getTypes(dictId) {
    getType(dictId).then((response: any) => {
      queryParams.value.dictType = response.data.dictType
      currentDictType.value = response.data.dictType
      onSearch()
    })
  }

  /** 查询字典类型列表 */
  function getTypeList() {
    getDictOptionselect().then((response: any) => {
      typeOptions.value = response.data
    })
  }

  /** 添加按钮操作 */
  function handleAdd() {
    reset()
    title.value = '添加参数'
    formDialogVisible.value = true
    form.value.dictType = queryParams.value.dictType
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const dictCode = row.dictCode || ids.value
    getData(dictCode).then((response: any) => {
      form.value = response.data
      formDialogVisible.value = true
      title.value = '修改字典数据'
    })
  }

  /** 导出按钮操作 */
  function handleExport() {
    console.log('export')
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const dictIds = row.dictCode || ids.value
    ElMessageBox.confirm('数据一经删除不可恢复，请再次确认！', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await delData(dictIds)
      useDictStore().removeDict(queryParams.value.dictType)
      onSearch()
    })
  }

  /** 改变分页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  /** 改变当前分页 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  /** 改变多选项 */
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.dictCode)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  async function onSearch() {
    loading.value = true
    const params = {
      ...queryParams.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const { rows, total } = await listData(params)
    dataList.value = rows
    pagination.total = total
    loading.value = false
    currentDictType.value = queryParams.value.dictType
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    onSearch()
  }

  onMounted(() => {
    onSearch()
    getTypes(route.params && route.params.dictId)
    getTypeList()
  })

  return {
    form,
    title,
    dictCode,
    currentDictType,
    loading,
    columns,
    multiple,
    dataList,
    pagination,
    queryParams,
    typeOptions,
    showSelection,
    formDialogVisible,
    sys_normal_disable,
    onSearch,
    resetForm,
    handleAdd,
    handleUpdate,
    handleDelete,
    handleExport,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
